import { Select } from "antd"
import { useEffect, useState } from "react";
import * as api from '../../../api';

export const SelectPage = () => {

    const [value, setValue] = useState<string>('');
    const [options, setOptions] = useState([]);

    const handleChange = (value: string) => {
        console.log(`selected ${value}`);
        const url = new URL(location.href);
        url.searchParams.set('id', value);
        location.href = url.toString();
    };

    useEffect(() => {
        api.list({userid: 6}).then((res) => {
            console.log('list', res);
            if (Array.isArray(res.data.data)) {
                const currentId = new URLSearchParams(location.search).get('id');
                const options = res.data.data.map((item: {id: number, title: string}) => {
                    if (item.id === Number(currentId)) {
                        setValue(item.title)
                    }
                    return {
                        value: item.id, 
                        label: item.title
                    }
                })
                setOptions(options);
            }
        })
    }, []);


    return <Select
        value={value}
        style={{ width: 120 }}
        onChange={handleChange}
        options={options}
    />
}